import 'package:flutter/cupertino.dart';
import 'package:flutter_menu/biz/order/order_controller.dart';
import 'package:flutter_menu/data/provider/category_provider.dart';
import 'package:flutter_menu/data/provider/electronic_provider.dart';
import 'package:flutter_menu/model/menu_model.dart';
import 'package:flutter_menu/utils/common_utils.dart';
import 'package:flutter_menu/widgets/load_container.dart';
import 'package:get/get.dart';

class SearchController extends GetxController {
  TextEditingController textFieldController = TextEditingController();
  OrderController orderController = OrderController.to;

  CategoryProvider categoryProvider = Get.find<CategoryProvider>();

  ElectronicProvider electronicProvider = Get.find<ElectronicProvider>();

  var dishResultList = <CategoryListProductList>[].obs;
  var searchQuery = "".obs;
  var cachedProductList = <CategoryListProductList>[];

  // 搜索页面控制器
  LoadController? loadSearchResultController = LoadController();

  bool isInputEmpty() {
    return searchQuery.value.isEmpty;
  }

  void updateSearchQuery(String text) {
    searchQuery.value = text.trim();
  }

  void search() {
    if (isInputEmpty()) {
      return;
    }
    hideKeyboard();
    onLoadSearchResultList();
  }

  Future<void> onLoadSearchResultList() async {
    debugPrint("onLoadSearchResultList: $searchQuery");
    if (loadSearchResultController?.isLoading() ?? false) {
      return;
    }
    loadSearchResultController?.loading();

    if (cachedProductList.isEmpty) {
      var elecMenuList = await electronicProvider.getElecMenuList();
      cachedProductList = categoryProvider.prepareProductList(
          allCustomMenus: orderController.customMenuList,
          electronicMenus: elecMenuList);
    }

    var prepareProductList = cachedProductList.where((product) {
      return product.imageName?.contains(searchQuery.value) ?? false;
    }).toList();

    if (prepareProductList.isEmpty) {
      // 空数据
      dishResultList.value = [];
      loadSearchResultController?.empty();
    } else {
      // 成功获取数据
      dishResultList.value = prepareProductList;
      loadSearchResultController?.complete();
    }
  }

  void onItemClick(CategoryListProductList? item) {
    if (item != null) {
      OrderController.to.showOrderDetail(item);
    }
  }

  @override
  void onClose() {
    super.onClose();
    loadSearchResultController?.dispose();
    loadSearchResultController = null;
  }

}
